﻿using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text;
using System.Management;
using System.Text.RegularExpressions;

namespace ClassLibrary
{
    /// <summary>
    /// IPProvider 的摘要说明。
    /// </summary>
    public class IPProvider
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public IPProvider()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 设置DNS
        /// </summary>
        /// <param name="dns"></param>
        public static void SetDNS(string[] dns)
        {
            SetIPAddress(null, null, null, dns);
        }

        /// <summary>
        /// 设置网关
        /// </summary>
        /// <param name="getway"></param>
        public static void SetGetWay(string getway)
        {
            SetIPAddress(null, null, new string[] { getway }, null);
        }

        /// <summary>
        /// 设置网关
        /// </summary>
        /// <param name="getway"></param>
        public static void SetGetWay(string[] getway)
        {
            SetIPAddress(null, null, getway, null);
        }

        /// <summary>
        /// 设置IP地址和掩码
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        public static void SetIPAddress(string ip, string submask)
        {
            SetIPAddress(new string[] { ip }, new string[] { submask }, null, null);
        }

        /// <summary>
        /// 设置IP地址，掩码和网关
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        /// <param name="getway"></param>
        public static void SetIPAddress(string ip, string submask, string getway)
        {
            SetIPAddress(new string[] { ip }, new string[] { submask }, new string[] { getway }, null);
        }

        /// <summary>
        /// 设置IP地址，掩码，网关和DNS
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        /// <param name="getway"></param>
        /// <param name="dns"></param>
        public static void SetIPAddress(string[] ip, string[] submask, string[] getway, string[] dns)
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            foreach (ManagementObject mo in moc)
            {
                //如果没有启用IP设置的网络设备则跳过
                if (!(bool)mo["IPEnabled"])
                    continue;

                //设置IP地址和掩码
                if (ip != null && submask != null)
                {
                    inPar = mo.GetMethodParameters("EnableStatic");
                    inPar["IPAddress"] = ip;
                    inPar["SubnetMask"] = submask;
                    outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                }

                //设置网关地址
                if (getway != null)
                {
                    inPar = mo.GetMethodParameters("SetGateways");
                    inPar["DefaultIPGateway"] = getway;
                    outPar = mo.InvokeMethod("SetGateways", inPar, null);
                }

                //设置DNS地址
                if (dns != null)
                {
                    inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                    inPar["DNSServerSearchOrder"] = dns;
                    outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                }
            }
        }

        /// <summary>
        /// 启用DHCP服务器
        /// </summary>
        public static void EnableDHCP()
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                //如果没有启用IP设置的网络设备则跳过
                if (!(bool)mo["IPEnabled"])
                    continue;

                //重置DNS为空
                mo.InvokeMethod("SetDNSServerSearchOrder", null);
                //开启DHCP
                mo.InvokeMethod("EnableDHCP", null);
            }
        }

        /// <summary>
        /// 判断是否IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string ip)
        {
            string[] arr = ip.Split('.');
            if (arr.Length != 4)
                return false;

            string pattern = @"\d{1,3}";
            for (int i = 0; i < arr.Length; i++)
            {
                string d = arr[i];
                if (i == 0 && d == "0")
                    return false;
                if (!Regex.IsMatch(d, pattern))
                    return false;

                if (d != "0")
                {
                    d = d.TrimStart('0');
                    if (d == "")
                        return false;

                    if (int.Parse(d) > 255)
                        return false;
                }
            }

            return true;
        }

        //禁用 SetNetworkAdapter(False)
        //启用 SetNetworkAdapter(True)
        //添加引用system32\shell32.dll 
        public static bool SetNetworkAdapter(bool status)
        {
            const string discVerb = "禁用(&B)"; // "停用(&B)";
            const string connVerb = "启用(&A)"; // "启用(&A)";
            const string network = "网络连接"; //"网络连接";
            const string networkConnection = "本地连接"; // "VMware Network Adapter VMnet1"

            string sVerb = null;

            if (status)
            {
                sVerb = connVerb;
            }
            else
            {
                sVerb = discVerb;
            }

            Shell32.Shell sh = new Shell32.Shell();
            Shell32.Folder folder = sh.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS);

            try
            {
                //进入控制面板的所有选项 
                foreach (Shell32.FolderItem myItem in folder.Items())
                {
                    //进入网络连接 
                    if (myItem.Name == network)
                    {
                        Shell32.Folder fd = (Shell32.Folder)myItem.GetFolder;
                        foreach (Shell32.FolderItem fi in fd.Items())
                        {
                            //找到本地连接 
                            if ((fi.Name == networkConnection))
                            {
                                //找本地连接的所有右键功能菜单 
                                foreach (Shell32.FolderItemVerb Fib in fi.Verbs())
                                {
                                    if (Fib.Name == sVerb)
                                    {
                                        Fib.DoIt();
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
            return true;
        }

        //#region "Public Methods"

        //public static void ToggleWirelessConnection()
        //{

        //    foreach (Shell32.FolderItemVerb verb in WirelessConnectionFolderItem.Verbs())
        //    {
        //        if (verb.Name == "启用(&A)" || verb.Name == "禁用(&B)")
        //        {
        //            verb.DoIt();
        //            goto endOfForLoop;
        //        }
        //    }
        //endOfForLoop:
        //    System.Threading.Thread.Sleep(1000);
        //}

        //public static void ToggleLocalAreaConnection()
        //{

        //    foreach (Shell32.FolderItemVerb verb in LocalAreaConnectionFolderItem.Verbs())
        //    {
        //        //FOR 2000
        //        //                if (verb.Name == "启用(&A)" || verb.Name == "禁用(&B)")
        //        //                {
        //        //                    verb.DoIt();
        //        //                    goto endOfForLoop;
        //        //                }
        //        //            }
        //        //endOfForLoop:
        //        //            System.Threading.Thread.Sleep(1000);

        //        if (verb.Name == "启用(&A)" || verb.Name == "停用(&B)")
        //        {
        //            verb.DoIt();
        //            goto endOfForLoop;
        //        }
        //    }
        //endOfForLoop:
        //    System.Threading.Thread.Sleep(1000);
        //}

        //#endregion

        //#region "Properties"

        //private static Shell32.Folder ControlPanelFolder
        //{
        //    get
        //    {
        //        Shell32.Shell shell = new Shell32.Shell();
        //        return shell.NameSpace(3);
        //    }
        //}

        //private static Shell32.Folder NetworkFolder
        //{

        //    get
        //    {
        //        Shell32.Folder retVal = null;

        //        foreach (Shell32.FolderItem fi in ControlPanelFolder.Items())
        //        {
        //            //WindowsXP及以上需将下面的字符串改为：“网络连接”，XP以下为"网络和拨号连接"
        //            if (fi.Name == "网络连接")
        //            {
        //                retVal = (Shell32.Folder)fi.GetFolder;
        //            }
        //        }

        //        if (retVal == null)
        //        {
        //            throw (new NetworkConnectionsFolderNotFoundException());
        //        }
        //        else
        //        {
        //            return retVal;
        //        }

        //    }
        //}

        //private static Shell32.FolderItem LocalAreaConnectionFolderItem
        //{
        //    get
        //    {

        //        Shell32.FolderItem retVal = null;
        //        Properties.Settings set = Properties.Settings.Default;
        //        foreach (Shell32.FolderItem folderItem in NetworkFolder.Items())
        //        {
        //            Console.WriteLine(folderItem.Name);
        //            if (folderItem.Name == set.networkname)
        //            {
        //                retVal = folderItem;
        //                goto endOfForLoop;
        //            }
        //        }
        //    endOfForLoop:

        //        if (retVal == null)
        //        {
        //            throw (new LocalAreaConnectionFolderItemNotFoundException());
        //        }
        //        else
        //        {
        //            return retVal;
        //        }

        //    }
        //}

        //private static Shell32.FolderItem WirelessConnectionFolderItem
        //{
        //    get
        //    {

        //        Shell32.FolderItem retVal = null;
        //        Properties.Settings set = Properties.Settings.Default;
        //        foreach (Shell32.FolderItem folderItem in NetworkFolder.Items())
        //        {
        //            Console.WriteLine(folderItem.Name);
        //            if (folderItem.Name == set.networkname)
        //            {
        //                retVal = folderItem;
        //                goto endOfForLoop;
        //            }
        //        }
        //    endOfForLoop:

        //        if (retVal == null)
        //        {
        //            throw (new WirelessConnectionFolderItemNotFoundException());
        //        }
        //        else
        //        {
        //            return retVal;
        //        }

        //    }
        //}

        //#endregion

        //#region "Custom Exceptions"

        //public class NetworkConnectionsFolderNotFoundException : Exception
        //{


        //    public override string Message
        //    {
        //        get
        //        {
        //            return "The Network Connections Folder Could Not Be Found!";
        //        }
        //    }
        //}

        //public class LocalAreaConnectionFolderItemNotFoundException : Exception
        //{


        //    public override string Message
        //    {
        //        get
        //        {
        //            return "The Local Area Connection Folder Could Not Be Found!";
        //        }
        //    }
        //}

        //public class WirelessConnectionFolderItemNotFoundException : Exception
        //{


        //    public override string Message
        //    {
        //        get
        //        {
        //            return "The Wireless Connection Folder Could Not Be Found!";
        //        }
        //    }
        //}

        //#endregion
    }
}